// subPages/bodyFat/index/index.js
import * as echarts from '../../../ec-canvas/echarts';
//获取应用实例
const app = getApp()
var jsonData = require('../../../data/json');
var template = require('../../../template/template.js');
var util =  require('../../../utils/util.js');
let Chart = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    weightTip: {
      tip:'无数据'
    },
    cBtnTxt: {
      cBtnTxt:'连接体脂秤'
    },
    processData: [{
      num: '18.5',
      line: 'white',
      marginLeft:'150rpx'
    },
    {
      num: '24',
      line: 'white',
      marginLeft:'110rpx'
    },
    {
      num: '27',
      line: 'white',
      marginLeft:'6rpx'
    }],
    ec: {
      // lazyLoad: true // 延迟加载
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (res) {
    template.bodyFatTabbar("tabBar", 0, this) //0表示第一个tabbar
    this.barchartsComponnet = this.selectComponent('#progressChart');
    this.getImage();
  },

  //获取最近一次体检信息
  getIndexList:function(){
    var that = this
    if(app.globalData.userId == ''||app.globalData.userId == null) return
    wx.request({
      url: app.globalData.apiUrl +'/bodycheck',
      data: {
        id: app.globalData.userId
      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data.code == '200'){
          var weightTip = 'weightTip.tip';
          that.setData({
            dataList: res.data.data.list,
            weight: res.data.data.list[0].value,
            [weightTip] : res.data.data.list[0].type,
            bmi: res.data.data.list[1].value,
            setBmi : (res.data.data.list[1].value / 0.4),
            bmitip: res.data.data.list[1].type,
            haveData: 1,
            id: res.data.data.id
          })
          that.setUtil(that.data.dataList);
          that.getGraphData();//初始化图表
          that.setLine(res.data.data.list[1].value);//设置线
        }
        else{
          that.setData({
            //jsonData.dataList获取json.js里定义的json数据，并赋值给list_data
            dataList: jsonData.dataList,
            weight: 0,
            bmi: 0,
            bmitip: '无数据',
            [weightTip]: '无数据',
            haveData: 2,
          });
          that.getGraphData();//初始化图表
        }

      },
      fail: function (res) {
        // console.log("失败",res);
        util.showModal('提示','数据请求失败，网络异常')
        return;
      }
    })
  },

  //设置单位
  setUtil:function(dataList){
    var that = this
    for(var i in dataList){
      if(dataList[i].title == '体重')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '（kg）',
          [show]: false
        })
      }
      if(dataList[i].title == 'BMI')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '',
          [show]: true
        })
      }
      if(dataList[i].title == '体脂率')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '（%）',
          [show]: true
        })
      }
      if(dataList[i].title == '肌肉量')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '（kg）',
          [show]: true
        })
      }
      if(dataList[i].title == '体年龄')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '（岁）',
          [show]: true
        })
      }
      if(dataList[i].title == '水分率')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '（%）',
          [show]: true
        })
      }
      if(dataList[i].title == '内脏脂肪')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '',
          [show]: true
        })
      }
      if(dataList[i].title == '骨量')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '（kg）',
          [show]: true
        })
      }
      if(dataList[i].title == '基础代谢')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '（kcal）',
          [show]: true
        })
      }
      if(dataList[i].title == '蛋白质率')
      {
        var util = "dataList[" + i + "].util"
        var show = "dataList[" + i + "].show"
        that.setData({
          [util]: '（%）',
          [show]: true
        })
      }
    }
  },

  //设置线
  setLine:function(bmi){
    if(bmi =='' || bmi == 0)return;
    var that = this
    if(bmi >= 18.6 && bmi < 25)
    {
      // that.data.processData[0]
      var line = 'processData[0].line';
      that.setData({
        [line] : '#ececec'
      })
    }
    else if(bmi >= 25 && bmi < 30)
    {
      var line = 'processData[0].line';
      var line1 = 'processData[1].line';
      that.setData({
        [line] : '#ececec',
        [line1] : '#ececec',
        [line2] : '#ececec'
      })
    }
    else if(bmi >= 30)
    {
      var line = 'processData[0].line';
      var line1 = 'processData[1].line';
      var line2 = 'processData[2].line';
      that.setData({
        [line] : '#ececec',
        [line1] : '#ececec',
        [line2] : '#ececec',
      })
    }
  },

  //图表
  getGraphData:function(){
    var that = this
    if (!Chart){
      that.init_echarts(); //初始化图表
    }else{
      that.setOption(); //更新数据
    }
  },

   //初始化图表
   init_echarts: function () {
    this.barchartsComponnet.init((canvas, width, height) => {
      // 初始化图表
        Chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      this.setOption();
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return Chart;
    });
  },

  setOption: function () {
    Chart.clear();  // 清除
    Chart.setOption(this.getOption());  //获取新数据
  },

  getOption: function () {
    var that = this
    var dataShadow = [];
    var yMax = 50;
    for (var i = 0; i < that.data.bmi.length; i++) {
        dataShadow.push(yMax);
    }
    // 指定图表的配置项和数据
    var option = {
      color: ['#fff'],
    	xAxis: {
        type : 'value',
        show: false,
        max: 50,
        min: 0,
      },
      yAxis: {
          type : 'category',
          show: false,
      },
      grid:{ 
        borderWidth:0,
        x:0,
        y:14,
        x2:20,
        y2:0,
        containLabel: true
      },
      series : [
        { // For shadow
          type: 'bar',
          itemStyle: {
              normal: {
              color: 'rgba(255,255,255,0.2)',
              barBorderRadius:15
            }
          },
          barGap:'-100%',
          data: [dataShadow],
          barWidth: 15,
          legendHoverLink:false,
          animation: false,
          z:-10
        },
        {
          type:'bar',
          itemStyle: {
            normal: {
              color: '#fff',
              barBorderRadius:15
            }
          },
          barWidth: 15,
          z: -5,
            // data: ['27']
          data:[that.data.bmi]
        }
      ]
    }
    return option;
  },

  //获得图片
  getImage:function(){
    var that = this
    wx.request({
      url: app.globalData.apiUrl +'/getadment',
      data: {

      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data.code == '200'){
          that.setData({
            imgSrc: res.data.data
          })
        }
      },
      fail: function (res) {
        console.log("失败");
      }
    })
  },

  //连接体脂秤
  connection: function () { 
    var that = this
    wx.navigateTo({
      url: '../connection/connection?weightTip=' + JSON.stringify(that.data.weightTip) +'&weight=' + that.data.weight
    }) 
  },

  //历史记录
  history: function () {
    wx.navigateTo({
      url: '../history/history'
    })  
  },

  //测量分析
  analysis:function(){
    var that = this
    if(that.data.haveData==1)
    {
      wx.navigateTo({
        url: '../analysis/analysis?id='+ that.data.id,
      }) 
    }
    else{
      wx.showToast({
        title: '暂无数据',
        icon: 'success',
      })
      setTimeout(function () {
        wx.hideToast()
      }, 2000)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getIndexList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    Chart = null
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    Chart = null
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: 'PAPN小程序',
      path: 'pages/index/index?puid=' + app.globalData.userId,
      success: function(res) {
          res.shareTickets 
      },
      fail: function(res) {
          console.log(res)
      }
    }
  }
})
